/**
 * 用户管理页面
 */
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Modal,
  Form,
  Tag,
  Switch,
  Popconfirm,
  message,
  Row,
  Col,
  Tooltip,
  Avatar
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  UserOutlined,
  MailOutlined,
  PhoneOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { User, UserCreate, UserUpdate, Role } from '../types/auth';
import { useAuth } from '../contexts/AuthContext';
import { showNotification } from '../utils/notification';
import api from '../services/api';
// import PerformanceMonitor from '../components/PerformanceMonitor';

import { requestGuard } from '../utils/requestGuard';

const { Search } = Input;
const { Option } = Select;

const UserManagement: React.FC = () => {
  const { hasPermission } = useAuth();
  const [users, setUsers] = useState<User[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [rolesLoading, setRolesLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedRole, setSelectedRole] = useState<number | undefined>();
  const [isActiveFilter, setIsActiveFilter] = useState<boolean | undefined>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  // 防抖搜索的ref
  const searchTimeoutRef = useRef<NodeJS.Timeout>();
  const fetchUsersRef = useRef<() => void>();

  // 防止重复请求的ref
  const isLoadingUsersRef = useRef(false);
  const isLoadingRolesRef = useRef(false);
  const rolesLoadedRef = useRef(false);

  // 权限检查 - 使用useMemo避免重复计算
  const permissions = useMemo(() => ({
    canViewUsers: hasPermission('user.view'),
    canCreateUsers: hasPermission('user.create'),
    canUpdateUsers: hasPermission('user.update'),
    canDeleteUsers: hasPermission('user.delete'),
  }), [hasPermission]);

  /**
   * 获取用户列表 - 使用requestGuard防止重复请求
   */
  const fetchUsers = useCallback(async () => {
    const currentParams = {
      page: pagination.current,
      page_size: pagination.pageSize,
      search: searchText || undefined,
      role_id: selectedRole,
      is_active: isActiveFilter,
    };

    // 使用requestGuard防止重复请求
    if (!requestGuard.canRequest('fetchUsers', currentParams)) {
      return;
    }

    setLoading(true);

    try {

      const response = await api.get('/v1/users', { params: currentParams });
      const data = response.data.data;

      setUsers(data.users);
      setPagination(prev => ({
        ...prev,
        total: data.total,
      }));
    } catch (error: any) {
      showNotification('error', '获取用户列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchUsers');
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, searchText, selectedRole, isActiveFilter]); // 添加所有依赖项

  /**
   * 获取角色列表 - 使用requestGuard防止重复请求
   */
  const fetchRoles = useCallback(async () => {
    // 如果已经加载过，直接返回
    if (rolesLoadedRef.current) {

      return;
    }

    // 使用requestGuard防止重复请求
    if (!requestGuard.canRequest('fetchRoles')) {
      return;
    }

    setRolesLoading(true);

    try {

      const response = await api.get('/v1/roles');
      setRoles(response.data.data.roles);
      rolesLoadedRef.current = true; // 标记已加载
    } catch (error: any) {
      console.error('获取角色列表失败:', error);
      showNotification('error', '获取角色列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchRoles');
      setRolesLoading(false);
    }
  }, []); // 移除所有依赖项

  // 触发数据获取的内部函数
  const triggerDataFetch = useCallback(() => {
    fetchUsers();
  }, [fetchUsers]);

  // 初始化数据获取 - 只在组件挂载时执行一次
  useEffect(() => {
    if (!permissions.canViewUsers) return;



    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchUsers');
    requestGuard.clearGuard('fetchRoles');

    // 获取角色数据（只获取一次）
    if (!rolesLoadedRef.current && !isLoadingRolesRef.current) {
      fetchRoles();
    }

    // 获取用户数据
    triggerDataFetch();
  }, [permissions.canViewUsers]); // 移除函数依赖，避免无限循环

  // 分页和搜索条件变化时获取用户数据
  useEffect(() => {
    if (!permissions.canViewUsers) return;


    fetchUsers();
  }, [permissions.canViewUsers, fetchUsers]);

  // 搜索和筛选条件变化时的处理 - 使用防抖
  useEffect(() => {
    if (!permissions.canViewUsers) return;



    // 清除之前的定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // 设置新的定时器
    searchTimeoutRef.current = setTimeout(() => {

      // 重置到第一页
      setPagination(prev => ({ ...prev, current: 1 }));
      // 注意：不在这里直接调用fetchUsers，让分页useEffect处理
    }, 300); // 300ms防抖

    // 清理函数
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, [permissions.canViewUsers, searchText, selectedRole, isActiveFilter]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);



  /**
   * 处理搜索 - 直接触发搜索并重置分页
   */
  const handleSearch = useCallback((value: string) => {

    setSearchText(value);
    // 重置到第一页
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  /**
   * 处理表格变化 - 使用useCallback优化
   */
  const handleTableChange = useCallback((paginationConfig: any) => {
    setPagination(prev => ({
      ...prev,
      current: paginationConfig.current,
      pageSize: paginationConfig.pageSize,
    }));
  }, []);

  /**
   * 打开创建/编辑模态框
   */
  const openModal = (user?: User) => {
    setEditingUser(user || null);
    setIsModalVisible(true);
    
    if (user) {
      form.setFieldsValue({
        ...user,
        role_ids: user.roles.map(role => role.id),
      });
    } else {
      form.resetFields();
    }
  };

  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalVisible(false);
    setEditingUser(null);
    form.resetFields();
  };

  /**
   * 提交表单
   */
  const handleSubmit = async (values: any) => {
    try {
      if (editingUser) {
        // 更新用户
        const updateData: UserUpdate = {
          email: values.email,
          full_name: values.full_name,
          phone: values.phone,
          department: values.department,
          position: values.position,
          is_active: values.is_active,
          role_ids: values.role_ids,
        };
        
        await api.put(`/v1/users/${editingUser.id}`, updateData);
        showNotification('success', '用户更新成功');
      } else {
        // 创建用户
        const createData: UserCreate = {
          username: values.username,
          email: values.email,
          password: values.password,
          full_name: values.full_name,
          phone: values.phone,
          department: values.department,
          position: values.position,
          role_ids: values.role_ids,
        };
        
        await api.post('/v1/users', createData);
        showNotification('success', '用户创建成功');
      }
      
      closeModal();
      // 刷新用户列表
      await fetchUsers();
    } catch (error: any) {


      // 详细的错误处理
      let errorMessage = '操作失败';
      let errorDetails = '';

      if (error.response?.data) {
        const data = error.response.data;

        // 处理422验证错误
        if (error.response.status === 422) {
          if (data.detail) {
            if (Array.isArray(data.detail)) {
              errorDetails = data.detail.map((err: any) => {
                const field = err.loc ? err.loc[err.loc.length - 1] : '未知字段';
                const message = err.msg || err.message || '验证失败';
                return `${field}: ${message}`;
              }).join('\n');
              errorMessage = '表单验证失败';
            } else if (typeof data.detail === 'string') {
              errorDetails = data.detail;
            }
          }
        } else {
          errorMessage = data.message || data.detail || errorMessage;
        }
      }

      showNotification('error', errorMessage, errorDetails || undefined);
    }
  };

  /**
   * 删除用户
   */
  const handleDelete = async (userId: number) => {
    try {
      await api.delete(`/v1/users/${userId}`);
      showNotification('success', '用户删除成功');
      await fetchUsers();
    } catch (error: any) {
      const message = error.response?.data?.message || '删除失败';
      showNotification('error', '删除失败', message);
    }
  };

  /**
   * 切换用户状态
   */
  const toggleUserStatus = async (user: User) => {
    try {
      const updateData: UserUpdate = {
        is_active: !user.is_active,
      };
      
      await api.put(`/v1/users/${user.id}`, updateData);
      showNotification('success', `用户已${user.is_active ? '禁用' : '启用'}`);
      await fetchUsers();
    } catch (error: any) {
      const message = error.response?.data?.message || '状态切换失败';
      showNotification('error', '状态切换失败', message);
    }
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      render: (text, record) => (
        <Space>
          <Avatar 
            src={record.avatar_url} 
            icon={<UserOutlined />}
            size="small"
          />
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>
              {record.full_name}
            </div>
          </div>
        </Space>
      ),
    },
    {
      title: '联系信息',
      key: 'contact',
      render: (_, record) => (
        <div>
          <div style={{ marginBottom: 4 }}>
            <MailOutlined style={{ marginRight: 4, color: '#1890ff' }} />
            {record.email}
          </div>
          {record.phone && (
            <div>
              <PhoneOutlined style={{ marginRight: 4, color: '#52c41a' }} />
              {record.phone}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '部门/职位',
      key: 'department',
      render: (_, record) => (
        <div>
          {record.department && <div>{record.department}</div>}
          {record.position && (
            <div style={{ fontSize: '12px', color: '#666' }}>
              {record.position}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles: Role[]) => (
        <Space wrap>
          {roles.map(role => (
            <Tag key={role.id} color="blue">
              {role.display_name}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (isActive: boolean, record) => (
        <Switch
          checked={isActive}
          onChange={() => toggleUserStatus(record)}
          disabled={!permissions.canUpdateUsers}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'last_login',
      key: 'last_login',
      render: (lastLogin: string) => (
        lastLogin ? new Date(lastLogin).toLocaleString() : '从未登录'
      ),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          {permissions.canUpdateUsers && (
            <Tooltip title="编辑">
              <Button
                type="text"
                icon={<EditOutlined />}
                onClick={() => openModal(record)}
              />
            </Tooltip>
          )}
          {permissions.canDeleteUsers && !record.is_superuser && (
            <Popconfirm
              title="确定要删除这个用户吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="删除">
                <Button
                  type="text"
                  danger
                  icon={<DeleteOutlined />}
                />
              </Tooltip>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  if (!permissions.canViewUsers) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <h3>权限不足</h3>
          <p>您没有查看用户的权限</p>
        </div>
      </Card>
    );
  }

  return (
      <div>
      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} sm={12} md={8}>
            <Search
              placeholder="搜索用户名、邮箱或姓名"
              allowClear
              onSearch={handleSearch}
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="选择角色"
              allowClear
              value={selectedRole}
              onChange={setSelectedRole}
              style={{ width: '100%' }}
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.display_name}
                </Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="用户状态"
              allowClear
              value={isActiveFilter}
              onChange={setIsActiveFilter}
              style={{ width: '100%' }}
            >
              <Option value={true}>启用</Option>
              <Option value={false}>禁用</Option>
            </Select>
          </Col>
          <Col xs={24} sm={12} md={4}>
            <Space>
              {permissions.canCreateUsers && (
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => openModal()}
                >
                  新建用户
                </Button>
              )}
              <Button
                icon={<ReloadOutlined />}
                onClick={() => fetchUsers()}
                loading={loading}
                title="刷新用户列表"
              />
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
      </Card>

      {/* 创建/编辑用户模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '新建用户'}
        open={isModalVisible}
        onCancel={closeModal}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          {!editingUser && (
            <>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, max: 50, message: '用户名长度为3-50个字符' },
                  {
                    pattern: /^[a-zA-Z0-9_-]+$/,
                    message: '用户名只能包含字母、数字、下划线和连字符'
                  }
                ]}
              >
                <Input placeholder="请输入用户名（3-50字符，字母数字下划线连字符）" />
              </Form.Item>
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 8, max: 128, message: '密码长度为8-128个字符' },
                  {
                    validator: (_, value) => {
                      if (!value) return Promise.resolve();

                      const errors = [];
                      if (!/[A-Z]/.test(value)) {
                        errors.push('至少包含一个大写字母');
                      }
                      if (!/[a-z]/.test(value)) {
                        errors.push('至少包含一个小写字母');
                      }
                      if (!/\d/.test(value)) {
                        errors.push('至少包含一个数字');
                      }
                      if (!/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(value)) {
                        errors.push('至少包含一个特殊字符');
                      }

                      if (errors.length > 0) {
                        return Promise.reject(new Error(`密码必须${errors.join('、')}`));
                      }

                      return Promise.resolve();
                    }
                  }
                ]}
              >
                <Input.Password placeholder="请输入密码（包含大小写字母、数字、特殊字符）" />
              </Form.Item>
            </>
          )}
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="full_name"
            label="真实姓名"
            rules={[
              { max: 100, message: '真实姓名不能超过100个字符' }
            ]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号码"
                rules={[
                  { max: 20, message: '手机号码不能超过20个字符' }
                ]}
              >
                <Input placeholder="请输入手机号码" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="department"
                label="部门"
                rules={[
                  { max: 100, message: '部门名称不能超过100个字符' }
                ]}
              >
                <Input placeholder="请输入部门" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="position"
            label="职位"
            rules={[
              { max: 100, message: '职位名称不能超过100个字符' }
            ]}
          >
            <Input placeholder="请输入职位" />
          </Form.Item>
          
          <Form.Item
            name="role_ids"
            label="角色"
            rules={[{ required: true, message: '请选择至少一个角色' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择角色"
              style={{ width: '100%' }}
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.display_name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          {editingUser && (
            <Form.Item
              name="is_active"
              label="用户状态"
              valuePropName="checked"
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
          )}
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={closeModal}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingUser ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      </div>
  );
};

export default UserManagement;
